<template>
    <!-- 信息发布 -->
    <view class="container">
        <!-- 标签切换 -->
        <view class="tabs">
            <view class="tab-item" :class="{ active: informationType == 0 }" @click="changeType(0)">求购</view>
            <view class="tab-item" :class="{ active: informationType == 1 }" @click="changeType(1)">收购</view>
            <view class="tab-item" :class="{ active: informationType == 2 }" @click="changeType(2)">批发</view>
            <view class="tab-item" :class="{ active: informationType == 3 }" @click="changeType(3)">询价</view>
        </view>


        <!-- 信息发布表单 -->
        <view class="relative pb-[210rpx] pt-[75rpx]">
  <image v-if="informationType == 0" src="https://xiangce223.oss-cn-hangzhou.aliyuncs.com/2025070411482709660.png" class="w-[750rpx] h-[894rpx] absolute z-[-1]"></image>
  <image v-else-if="informationType == 1" src="https://falvren.oss-cn-beijing.aliyuncs.com/2025062510114482a32.png" class="w-[750rpx] h-[894rpx] absolute z-[-1]"></image>
  <image v-else-if="informationType == 2" src="https://xiangce223.oss-cn-hangzhou.aliyuncs.com/2025070411235615d41.png" class="w-[750rpx] h-[894rpx] absolute z-[-1]"></image>
  <image v-else-if="informationType == 3" src="https://falvren.oss-cn-beijing.aliyuncs.com/202506251012579e9c2.png" class="w-[750rpx] h-[894rpx] absolute z-[-1]"></image>
  <view class="mx-[32rpx] mt-[184rpx]">
                <!-- 只保留求购和收购的提示信息 -->
                <view v-if="informationType == 0" style="border-radius: 20rpx 20rpx 0rpx 0rpx;"
                    class="text-[24rpx] text-[#E95555] pl-[80rpx] pt-[18rpx] pb-[14rpx] pr-[78rpx] bg-[#FDF3F2]">
                    求购用于定金找车、定金求购等具体求购信息发布
                </view>
            </view>

            <!-- 批发页面表单 -->
            <view class="mx-[32rpx] bg-[#FFFFFF] p-[24rpx] rounded-[20rpx]">
                <template v-if="informationType == 2">
                    <!-- VIN码 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333] w-[150rpx]">车辆识别码:</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[350rpx]" v-model="formData.vin" type="text"
                                placeholder="请输入车辆识别码（VIN）" />
                            <!-- <text class="ml-[10rpx] text-[#FF9500] text-[24rpx]">查重</text> -->
                        </view>
                    </view>

                    <!-- 品牌车型 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100"  @click="push('/pages_qc/wanttobuy/cardList')">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">品牌车型</text>
                        </view>
                        <view class="flex items-center">
                            <text class="text-[28rpx] w-[450rpx] text-[#333] text-end truncate">{{ formData.brandModel || '点击选择车型' }}</text>
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>

                    <!-- 上牌时间 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100"
                        @click="datetimeShow = true">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">上牌时间</text>
                        </view>
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#999]">{{ formData.registrationDate || '请选择上牌时间' }}</text>
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>

                    <!-- 表显里程 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">表显里程</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[200rpx]" v-model="formData.mileage"
                                placeholder="请输入表显里程" />
                            <text class="ml-[10rpx] text-[#999]">万公里</text>
                        </view>
                    </view>

                    <!-- 车身颜色 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">车身颜色</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[200rpx]" v-model="formData.color"
                                placeholder="请输入车身颜色" />
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>

                    <!-- 批发价 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">批发价</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[200rpx]" v-model="formData.price"
                                placeholder="请输入批发价格" />
                            <text class="ml-[10rpx] text-[#999]">万元</text>
                        </view>
                    </view>

                    <!-- 批发价选择 -->
                    <view class="mt-[24rpx] flex">
                        <view class="price-btn" :class="{ active: formData.transmissionType == 0 }"
                            @click="formData.transmissionType = 0">手动
                        </view>
                        <view class="price-btn ml-[24rpx]" :class="{ active: formData.transmissionType == 1 }"
                            @click="formData.transmissionType = 1">自动</view>
                    </view>
                    <!-- 排量 -->
                    <view
                        class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100 mt-[24rpx]">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">排量(T)</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[200rpx]" type="number"
                                v-model="formData.displacement" placeholder="请输入排量(T)" />
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>

                    <!-- 排放标准 -->
                    <view class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100"
                        @click="show = true">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">排放标准</text>
                        </view>
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">{{ formData.emissionStandard }}</text>
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>

                    <!-- 提示信息 -->
                    <!-- <view class="mt-[32rpx] bg-[#F5F5F5] p-[16rpx] rounded-[8rpx] text-[24rpx] text-[#999]">
                    填写车辆重点信息、车况优势、价格优势，请勿填写联系方式等个人信息
                </view> -->
                    <view>
                        <up-textarea style="background: #F5F5F7!important" v-model="formData.description"
                            placeholder="填写车辆重点信息、车况优势、价格优势，请"></up-textarea>
                    </view>
                </template>
                <template v-else>
                    <!-- 根据不同类型显示不同placeholder -->
                    <up-textarea maxlength="500" height="292rpx" v-model="formData.description"
                        :placeholder="getPlaceholder()" count></up-textarea>
                    <!-- 根据不同类型显示不同的车系选择 -->
                    <view style="background: linear-gradient( 180deg, #000000 0%, #585858 100%);border-radius: 12rpx;"
                        class="w-[638rpx] h-[104rpx] mt-[28rpx] flex justify-between items-center"
                        @click="push('/pages_qc/wanttobuy/cardList')">
                        <view class="text-[#FFFFFF] font-[500] text-[28rpx] pl-[28rpx]">
                            {{ informationType == 0 ? `${formData.brandModel || '请选择求购车系'}` :
                                informationType == 1 ? `${formData.brandModel || '请选择收购车系'}` : `${formData.brandModel
                                    || '请选择询价车系'}` }}
                        </view>
                        <image class="w-[263.93rpx] h-[60rpx] mr-[-150rpx]" src="@/static/images/index_bg/qccc.png">
                        </image>
                        <view class="text-[#FFFFFF] text-[28rpx] pr-[24rpx]">></view>
                    </view>

                </template>

                <view class="mt-[32rpx]">
                    <up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
                        :maxCount="9" width="145rpx" maxSize="10485760" uploadIcon="plus" uploadIconColor="#f4f4f5"
                        @oversize="oversize" height="145rpx" :multiple="true">
                        <image class="w-[145rpx] h-[145rpx]" src="@/static/images/img/xg.png"></image>
                    </up-upload>
                </view>
                <!-- 谁都可以看 -->
                <view
                    class="privacy-setting mt-[32rpx] flex justify-between items-center border-b border-gray-200 py-[20rpx]">
                    <view class="flex items-center"
                        @click="formData.visibility == 0 ? formData.visibility = 1 : formData.visibility = 0">
                        <text class="text-[28rpx] text-[#333]">谁可以看(点击切换)</text>
                        <text class="text-[28rpx] text-[#999] ml-[20rpx]">{{
                            formData.visibility == 0 ? '公开 (所有人可见)' : '私有 (仅自己可见)' }}</text>
                    </view>
                    <view class="text-[28rpx] text-[#999]">></view>
                </view>

                <!-- 高级设置 -->
                <view v-if="informationType == 0" class="advanced-setting mt-[20rpx] flex justify-between items-center">
                    <view class="flex items-center">
                        <text class="text-[28rpx] text-[#333]">高级设置</text>
                        <text class="text-[24rpx] text-[#999] ml-[20rpx]">选择高级设置中可加更多要求</text>
                    </view>
                    <switch @change="toggleAdvancedSetting" :checked="advancedSetting" color="#FFD856"
                        style="transform:scale(0.8)" />
                </view>
                <template v-if="informationType == 0 && advancedSetting">
                    <view
                        class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100 mt-[24rpx]">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">年份要求</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[450rpx]" type="number"
                                v-model="formData.yearRequirement" placeholder="(选填)请输入要求，如5年以内" />
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>
                    <view
                        class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100 mt-[24rpx]">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">里程要求</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[450rpx]" type="number"
                                v-model="formData.mileageRequirements" placeholder="(选填)请输入要求，如10万公里内" />
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>
                    <view
                        class="form-item flex justify-between items-center py-[24rpx] border-b border-gray-100 mt-[24rpx]">
                        <view class="flex items-center">
                            <text class="text-[28rpx] text-[#333]">车身颜色</text>
                        </view>
                        <view class="flex items-center">
                            <input class="text-[28rpx] text-right w-[450rpx]" type="number" v-model="formData.color"
                                placeholder="(选填)请输入要求，如黑色或白色" />
                            <text class="ml-[10rpx] text-[#999]">></text>
                        </view>
                    </view>
                </template>
            </view>

            <!-- 求购、收购、询价页面 -->
            <!-- <view v-if="informationType != 2" class="mx-[32rpx] bg-[#FFFFFF] p-[24rpx]">

            </view> -->
        </view>

        <!-- 底部发布按钮 -->
        <view class="fixed bottom-0 bg-[#FFFFFF] w-[750rpx] h-[196rpx] pt-[54rpx]">
            <view class="mx-[32rpx] h-[88rpx]">
                <up-button @click="publish" text="发布" :customStyle="{
                    color: '#FFEFB8',
                    paddingtop: '20rpx',
                    fontWeight: '500',
                    borderRadius: '16rpx',
                    fontSize: '32rpx',
                    lineHeight: '40rpx',
                    background: '#1A1A1A'
                }"></up-button>
            </view>
        </view>
    </view>
    <up-datetime-picker :minDate="new Date(`1990-01-01`).getTime()" @cancel="datetimeShow = false" @confirm="confirm"
        :maxDate="new Date().getTime()" :show="datetimeShow" closeOnClickOverlay @close="datetimeShow = false"
        v-model="formData.registrationDate" mode="date"></up-datetime-picker>
    <up-picker :show="show" closeOnClickOverlay @cancel="show = false" @confirm="confirm2" @close="show = false"
        :columns="[['国一', '国二', '国三', '国四', '国五', '国六']]"></up-picker>
</template>

<script setup>
import { ref, computed, } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { uploadImage } from '@/api/app';
import { carList, postPublish } from '@/api/whoable';
// 日期选择
const datetimeShow = ref(false);
const confirm = (e) => {
    console.log(e);
    formData.value.registrationDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
    datetimeShow.value = false;
};
const show = ref(false);
const confirm2 = (e) => {
    show.value = false;
    formData.value.emissionStandard = e.value[0]
}
// 跳转
const push = (path) => {
    uni.navigateTo({
        url: path
    });
};
// 上传
const fileList = ref([]);
const deletePic = (event) => {
    fileList.value.splice(event.index, 1);
};
const oversize = (file, lists, name) => {
    uni.$u.toast('图片大小超过限制！');
};
// 新增图片
const loadingUpload = ref(false);
const afterRead = async (event) => {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    try {
        let lists = [].concat(event.file);
        let fileListLen = fileList.value.length;
        lists.map((item) => {
            fileList.value.push({
                ...item,
                status: 'uploading',
                message: '上传中'
            });
        });
        loadingUpload.value = true;
        for (let i = 0; i < lists.length; i++) {
            const { data } = await uploadImage(lists[i].url);
            let item = fileList.value[fileListLen];
            fileList.value.splice(fileListLen, 1, {
                ...item,
                status: 'success',
                message: '',
                url: data
            });
            fileListLen++;
        }
    } catch (error) {
        loadingUpload.value = false;
    } finally {
        loadingUpload.value = false; // 确保无论成功或失败都会关闭加载状态
    }
};
const uploadFilePromise = (url) => {
    return '111';
};
// 表单数据
const formData = ref({
    brandModel: '',        // 品牌车型
    brand:'',
    vin: null,               // 车辆识别号（VIN）
    registrationDate: null,  // 上牌时间
    mileage: null,           // 表显里程
    color: null,             // 车身颜色
    price: null,             // 批发价（分）
    description: '',       // 车辆信息描述
    visibility: 0,           // 可见性（0-公开 1-私有）
    // userId: null,            // 发布人id
    // userName: null,          // 发布人姓名
    // avatar: null,            // 发布人头像
    transmissionType: 0,  // 变速箱类型（0-手动 1-自动）
    informationType: 0,      // 信息类型（0-求购 1-收购 2-批发 3询价）
    displacement: null,      // 排量
    emissionStandard: '国六',  // 排放标准
    image: null,             // 图片
    yearRequirement: null,   // 年份要求
    mileageRequirements: null, // 里程要求
    enableSettings: 0
})
const value2 = ref('');
// 信息类型（0-求购 1-收购 2-批发 3询价）
const informationType = ref(0);

// 批发页面表单数据
const vinCode = ref('');
const mileage = ref('');
const price = ref('');
const priceType = ref('manual'); // 手动或自动

// 输入内容
const content = ref('');
const contentLength = computed(() => content.value.length);



// 页面加载时获取传递的参数
onLoad((options) => {
    if (options.informationType !== undefined) {
        // 将字符串转换为数字
        informationType.value = parseInt(options.informationType);
    }
});

// 切换信息类型
const changeType = (type) => {
    informationType.value = type;
    // 切换类型时清空输入内容
    value2.value = '';
};

// 根据类型获取不同的placeholder
const getPlaceholder = () => {
    switch (informationType.value) {
        case 0:
            return "填写详细的求购需求，请勿输入联系方式等个人信息，如您需要发布长期收购信息，请点击上方收购";
        case 1:
            return "填写详细的长期收车需求，请勿填写联系方式等个人信息，相同收购需求请勿重复发布。";
        case 2:
            return "填写详细的批发信息，请勿输入联系方式等个人信息";
        case 3:
            return "填写详细的询价需求，请勿输入联系方式等个人信息";
        default:
            return "";
    }
};

// 选择车系
const selectCarSeries = () => {
    uni.showToast({
        title: '选择车系功能待实现',
        icon: 'none'
    });
};

// 切换高级设置
const toggleAdvancedSetting = (e) => {
    formData.value.enableSettings = e.detail.value;
};

// 发布信息

// brandModel: '奥迪 奥迪A3 2025款 A3L Limousine 基本型',        // 品牌车型
//     vin: null,               // 车辆识别号（VIN）
//     registrationDate: null,  // 上牌时间
//     mileage: null,           // 表显里程
//     color: null,             // 车身颜色
//     price: null,             // 批发价（分）
//     description: '',       // 车辆信息描述
//     visibility: 0,           // 可见性（0-公开 1-私有）
//     userId: null,            // 发布人id
//     userName: null,          // 发布人姓名
//     avatar: null,            // 发布人头像
//     transmissionType: null,  // 变速箱类型（0-手动 1-自动）
//     informationType: 0,      // 信息类型（0-求购 1-收购 2-批发 3询价）
//     displacement: null,      // 排量
//     emissionStandard: null,  // 排放标准
//     image: null,             // 图片
//     yearRequirement: null,   // 年份要求
//     mileageRequirements: null // 里程要求
const publish = async () => {
    try {
        if (informationType.value == 2) {
            // 批发页面验证
            if (!formData.value.vin) return uni.$u.toast('请输入车辆识别码VIN');
            if (!formData.value.brandModel) return uni.$u.toast('请选择品牌车型');
            if (!formData.value.registrationDate) return uni.$u.toast('请选择上牌时间');
            if (!formData.value.mileage) return uni.$u.toast('请输入里程');
            if (!formData.value.color) return uni.$u.toast('请输入车身颜色');
            if (!formData.value.price) return uni.$u.toast('请输入批发价');
            if (!formData.value.transmissionType && formData.value.transmissionType != 0) return uni.$u.toast('请选择变速箱类型');
            if (!formData.value.displacement) return uni.$u.toast('请输入排量');
            if (!formData.value.emissionStandard) return uni.$u.toast('请选择排放标准');
            if (!formData.value.description) return uni.$u.toast('请填写车辆描述');
            if (fileList.value.length == 0) return uni.$u.toast('请上传至少1张图片');
            formData.value.image = fileList.value.map(item => item.url).join(',');
            formData.value.price = Number(formData.value.price).toFixed(0) * 100;
        } else {
            // 其他页面验证
            if (!formData.value.description) return uni.$u.toast('请填写车辆描述');
            if (fileList.value.length == 0) return uni.$u.toast('请上传至少1张图片');
            formData.value.image = fileList.value.map(item => item.url).join(',');
        }
        formData.value.informationType = informationType.value;
        uni.showLoading({
            title: '请稍后...',
            mask: true
        });
        await postPublish(formData.value).then(res => {
            if (res.code == 200) {
                uni.hideLoading();
                uni.showToast({
                    title: '发布成功',
                    icon: 'none',
                    duration: 2000,
                    mask: true,
                    success: () => {
                        setTimeout(() => {
                            uni.navigateBack();
                        }, 2000);
                    }
                });
            } else {
                uni.hideLoading();
                uni.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000,
                    mask: true
                });
            }
        })
        console.log(formData.value);
    } catch (error) {
        uni.hideLoading();
        console.log(error);
    } 
};
uni.$on('getCarInfo', (data) => {
    console.log(data);
    formData.value.brandModel = `${data.series} ${data.models}`;
    formData.value.brand = data.brand;
});
</script>
<style lang="scss">
.u-textarea {
    background-color: #F5F5F7 !important;
}
</style>
<style lang="scss" scoped>
.container {
    display: flex;
    flex-direction: column;
    padding-bottom: 120rpx; // 为底部按钮留出空间
}

.tabs {
    display: flex;
    background-color: #FFFFFF;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 75rpx;
    z-index: 2;

    .tab-item {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        font-size: 30rpx;
        position: relative;

        &.active {
            color: #000;
            font-weight: bold;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 36rpx;
                height: 8rpx;
                background: #FFC915;
                border-radius: 3rpx;
            }
        }
    }
}

.privacy-setting,
.advanced-setting {
    border-bottom: 1rpx solid #f0f0f0;
}

.price-btn {
    width: 120rpx;
    height: 60rpx;
    background: #F5F5F5;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    font-size: 28rpx;
    color: #333;

    &.active {
        background: #000;
        color: #FFF;
    }
}
</style>